/*
 * crt0.c
 *
 * Copyright (C) 2017 Aleksandar Andrejevic <theflash@sdf.lonestar.org>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "crt_priv.h"
#include <stdlib.h>
#include <string.h>

int __CRT_PRIVATE(initialize_heap)(void);
int __CRT_PRIVATE(initialize_files)(process_params_t *params);
int main(int argc, char **argv);

void process_startup(process_params_t *params)
{
    int argc = 1;
    char *ptr;
    int space = 1;

    if (__CRT_PRIVATE(initialize_heap)() < 0) syscall_terminate(INVALID_HANDLE, 255);
    if (__CRT_PRIVATE(initialize_files)(params) < 0) syscall_terminate(INVALID_HANDLE, 255);

    for (ptr = params->command_line; *ptr; ptr++)
    {
        if (space != (__CRT_PUBLIC(isspace)(*ptr) != 0))
        {
            argc++;
            space = !space;
        }
    }

    char **argv = (char**)__builtin_alloca(argc * sizeof(char*));
    argc = 0;

    for (ptr = __CRT_PUBLIC(strtok)(params->command_line, " \t\r\n\v\f"); ptr != NULL; ptr = __CRT_PUBLIC(strtok)(NULL, " \t\r\n\v\f"))
    {
        if (*ptr) argv[argc++] = ptr;
    }

    argv[argc] = NULL;

    int exit_code = main(argc, argv);
    __CRT_PUBLIC(exit)(exit_code);
}
